package com.ruoyi.game.core.card;

import com.ruoyi.game.core.GameSetCore;
import com.ruoyi.game.core.GameSetPos;
import com.ruoyi.game.core.GameRoundCore;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.game.core.card.BasePoker.*;

/**
 * 单张牌出牌策略
 */
@Slf4j
public class DanCardTypeImpl extends BaseCardType {

    @Override
    public String getName() {
        return "单张";
    }

    @Override
    public List<Integer> firstAutoOut(GameSetPos pos) {
        GameSetCore set = pos.getGameSet(); // 你可以在 GameSetPos 中提前绑定或传入
        if (set == null) {
            log.warn("[DanCardType] 玩家 {} 无法获取所属对局，跳过首出", pos.getPlayerId());
            return Collections.emptyList();
        }

        // 按主值排序（从大到小），值为 0~18（大小王、A~2）
        Map<Integer, List<Integer>> grouped = pos.getHandCards().stream()
                .collect(Collectors.groupingBy(c -> getCardValueEx(c)));

        for (int i = 18; i >= 0; i--) {
            List<Integer> group = grouped.get(i);
            if (group != null && !group.isEmpty()) {
                String desc = BasePoker.getCardDescription(group.get(0));
                log.info("[DanCardType] 玩家 {} 自动首出单张：{}", pos.getPlayerId(), desc);
                return List.of(group.get(0));
            }
        }

        // 兜底：出最后一张
        Integer fallback = pos.getHandCards().get(pos.getHandCards().size() - 1);
        log.info("[DanCardType] 玩家 {} 无法按值匹配，兜底出最后一张：{}", pos.getPlayerId(), BasePoker.getCardDescription(fallback));
        return List.of(fallback);
    }

    @Override
    public List<Integer> followAutoOut(GameSetPos pos, GameRoundCore round) {
        // 跟牌时根据首出花色跟最小的该花色牌；否则出最大牌压人
        List<Integer> sameColor = getFollowableCards(pos, round);

        int chosen;
        if (!sameColor.isEmpty()) {
            chosen = sameColor.stream()
                    .min(Comparator.comparingInt(BasePoker::getCardValueEx))
                    .orElse(sameColor.get(0));
            log.info("[DanCardType] 玩家 {} 自动跟牌，选择花色最小的牌：{}", pos.getPlayerId(), BasePoker.getCardDescription(chosen));
        } else {
            // 无法跟花色，出最大一张压制
            chosen = pos.getHandCards().get(pos.getHandCards().size() - 1);
            log.info("[DanCardType] 玩家 {} 无法跟牌，改为打出最大压制牌：{}", pos.getPlayerId(), BasePoker.getCardDescription(chosen));
        }

        return List.of(chosen);
    }
}
